package com.guangwei.arithmetictest;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class TimeLineActivity extends AppCompatActivity {
    private final static String TAG = "TimeLineActivity";
    //存储列表数据
    List<TimeData> list = new ArrayList<>();
    TimeAdapter adapter;

    private static final String FILE_FOLDER =
            Environment.getExternalStorageDirectory().getAbsolutePath()
                    + File.separator + "ArithmeticTest" + File.separator + "data";
    private static final String SUMMARY_CSV = "summary.csv";
    private static final String DETAIL_CSV = "detail.csv";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_time_line);

        RecyclerView rlView = (RecyclerView) findViewById(R.id.activity_rlview);

        //初始化数据
        initData();
        // 将数据按照时间排序
        TimeComparator comparator = new TimeComparator();
        Collections.sort(list, comparator);
        // recyclerview绑定适配器
        rlView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new TimeAdapter(TimeLineActivity.this, list);
        rlView.setAdapter(adapter);

        adapter.setOnItemClickListener(new TimeAdapter.OnItemClickListener() {
            @Override
            public void onClick(int position) {
                //String postTime = list.get(position).getPosttime();
                //String title = list.get(position).getTitle();
                //Toast.makeText(TimeLineActivity.this, "click " + position + ": " + title, Toast.LENGTH_SHORT).show();
                String rawData = list.get(position).getRawData();

                String[] strList = rawData.split(",");
                if (strList.length > 6) {
                    String timeStamp = strList[0];
                    Integer correctCount = Integer.parseInt(strList[2]);
                    Integer wrongCount = Integer.parseInt(strList[3]);
                    Integer totalDuration = Integer.parseInt(strList[4]);

                    launchTestResultActivity(timeStamp, correctCount, wrongCount, totalDuration);
                }
            }
        });


        adapter.setOnItemLongClickListener(new TimeAdapter.OnItemLongClickListener() {
            @Override
            public void onClick(int position) {
                //String rawData = list.get(position).getRawData();
                //Toast.makeText(TimeLineActivity.this, "long click " + position + ": " + rawData , Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void initData() {
        ReadSummaryCSVThread csvReadSummaryThread = new ReadSummaryCSVThread(FILE_FOLDER, SUMMARY_CSV);
        csvReadSummaryThread.run();
    }

    class ReadSummaryCSVThread extends Thread {
        String fileName;
        String folder;
        public ReadSummaryCSVThread(String folder, String fileName) {
            this.folder = folder;
            this.fileName = fileName;
        }
        @Override
        public void run() {
            super.run();
            File inFile = new File(folder + File.separator + fileName);
            final StringBuilder cSb = new StringBuilder();
            String inString;
            try {
                BufferedReader reader =  new BufferedReader(new FileReader(inFile));
                while ((inString = reader.readLine()) != null) {
                    String[] strList = inString.split(",");
                    if (strList.length > 6) {
                        String timeStamp = strList[0];
                        String totalQuestion = strList[1];
                        String correctAnswer = strList[2];
                        String strTotalDuration = strList[4];

                        // timestamp format is "yyyy-MM-dd HH:mm:ss"
                        String strDate = timeStamp.split(" ")[0];
                        strDate = strDate.split("-")[0] + strDate.split("-")[1] + strDate.split("-")[2];
                        String time = timeStamp.split(" ")[1];

                        String title = time + "  总共" + totalQuestion + "道题，答对" + correctAnswer + "道题，用时";
                        int totalDuration = Integer.parseInt(strTotalDuration);
                        int minutes = totalDuration/60;
                        int seconds = totalDuration%60;
                        if (minutes>0) title += Integer.toString(minutes) + "分";
                        if (seconds>0) title += Integer.toString(seconds) + "秒";

                        list.add(new TimeData(strDate, title, inString));
                    }
                }
                reader.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    //mCSVTv.setText(cSb.toString());// 显示
                    //Log.i(TAG, cSb.toString());
                }
            });
        }
    }

    public void launchTestResultActivity(String timeStamp, int correctCount, int wrongCount, int duration) {
        Intent intent = new Intent();
        intent.setAction("score_result_action");
        intent.addCategory("score_result_category");
        Bundle bd = new Bundle();

        int minutes = duration/60;
        int seconds = 0;
        String strFinalScore = "";
        if (minutes > 0) {
            seconds = duration % 60;
            strFinalScore = String.format(getString(R.string.result_content_add_minute), correctCount, wrongCount, minutes, seconds);
        } else {
            seconds = duration;
            strFinalScore = String.format(getString(R.string.result_content), correctCount, wrongCount, seconds);
        }
        //SystemTTS.getInstance(this).speak(strFinalScore);

        bd.putString("score", strFinalScore);
        bd.putString("timeStamp", timeStamp);
        intent.putExtras(bd);
        startActivity(intent);
    }

}
